<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="ctx" th:content="${#httpServletRequest.getContextPath()}"/>
    <title>部门管理</title>
    <link rel="stylesheet" th:href="@{/css/admin/base-v2.css}">
    <link rel="stylesheet" th:href="@{/lib/font-awesome/4.7.0/css/font-awesome.min.css}">
    <link rel="stylesheet" th:href="@{/css/admin/app.css}">
</head>

<body>

<div class="app-page">

    <div class="app-page-content">

        <div class="app-card">
            <div class="app-card-body">
                <div class="app-card-body-con">
                    <!-- 过滤器 -->
                    <form class="filter">
                        <div class="filter-group">
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>状态</label></div>
                                    <div class="flex1">
                                        <select name="status" id="">
                                    <option value="">全部</option>
                                    <option value="0">启用</option>
                                    <option value="1">禁用</option>
                                </select>
                                    </div>
                                </div>
                            </div>
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>部门名称</label></div>
                                    <div class="flex1">
                                        <input type="text" placeholder="部门名称" name="departmentName">
                                    </div>
                                </div>
                            </div>
                            <div style="display: none">
                                <input name="pageNum" th:value="${pageNum}">
                                <input name="pageSize" th:value="${pageSize}">
                            </div>
                            <div class="filter-item">
                                <button class="z-btn z-primary">查询</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="app-card">
            <div class="app-card-body">
                <div class="app-card-body-con">

                    <div class="z-btn-group">
                        <a data-title="创建部门" class="j-btn-control z-btn z-default btn-add">创建部门</a>
                        <a data-title="批量启用" class="j-btn-control z-btn z-default btn-batch-able">批量启用</a>
                        <a data-title="批量禁用" class="j-btn-control z-btn z-default btn-batch-disable">批量禁用</a>
                    </div>

                    <table class="z-table">
                        <thead>
                        <tr>
                            <th>
                                <input type="checkbox" class="input j-checkbox-all">
                            </th>
                            <th>部门名称</th>
                            <th>部门代码</th>
                            <!--<th>上级部门</th>-->
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr th:each="department: ${departmentList}" th:attr="data-id=${department.departmentId}, data-departmentname=${department.departmentName},
                        data-departmentcode=${department.departmentCode},data-status=${department.status}">
                            <td>
                                <input type="checkbox" class="input j-checkbox">
                            </td>
                            <td th:text="${department.departmentName}"></td>
                            <td th:text="${department.departmentCode}"></td>
                            <!--注释上级部门，以后需要，再启用-->
                            <!--<td th:text="${department.parentDepartmentName}"></td>-->
                            <div th:switch="${department.status}">
                                <td th:case="1">禁用</td>
                                <td th:case="0">启用</td>
                            </div>
                            <td class="btn-group" th:switch="${department.status}">
                                <a class="btn-enable" th:case="1">启用</a>
                                <a class="btn-disable" th:case="0">禁用</a>
                                <a class="btn-detail">修改</a>
                            </td>
                        </tr>
                        </tbody>
                    </table>

                    <!-- 分页 -->
                    <div class="app-card-body">
                        <div class="pagination z-pat z-fr"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>


<!--新增/编辑-->
<div class=" popup-default z-popup z-fixed z-df z-flex-cc z-hide">
    <div class="bg" data-popup-close=""></div>
    <div class="section popup-add z-hide">
        <div class="title">创建部门</div>
        <div class="content" id="departmentForm">
            <form>
                <div class="form-item row" style="display: none">
                    <div class="label">
                        <label>ID</label>
                    </div>
                    <div class="body">
                        <input type="hidden" name="departmentId" class="departmentId">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>部门名称</label>
                    </div>
                    <div class="body">
                        <input type="text" placeholder="请输入部门名称" class="departmentName"
                               name="departmentName" data-name="部门名称" data-rule="required,length" minlength="1"
                               maxlength="32">

                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>部门代码</label>
                    </div>
                    <div class="body">
                        <input type="text" placeholder="请输入部门代码" class="departmentCode" name="departmentCode"
                               data-name="部门代码" data-rule="length" maxlength="32">

                    </div>
                </div>
                <!--注释上级部门，以后需要，再启用-->
                <!--<div class="form-item row">
                    <div class="label">
                        <label>上级部门</label>
                    </div>
                    <div class="body">
                        <input type="hidden" class="parentId z-hide parentId" name="parentId">
                        <div class="input-group">
                            <input type="text" disabled="disabled" class="parentName" name="parentName">
                            <span class="input-group-addon select-parent"><i class="fa fa-align-center"></i></span>
                        </div>
                    </div>
                </div>-->
                <!--注释选择城市，目前不需要这一功能-->
                <!--<div class="form-item row">
                    <div class="label">
                        <label>选择城市</label>
                    </div>
                    <div class="body">
                        <input type="hidden" class="z-hide cityCodes" name="cityCodes">
                        <input type="hidden" name="cityNames">
                        <div class="input-group">
                            <input type="text" disabled="disabled" class="areaNames" name="cityNames1" id="cityNames1" data-name="城市" data-rule="required" placeholder="请选择城市">
                            <span class="input-group-addon select-city"><i class="fa fa-align-center"></i></span>
                        </div>
                    </div>
                </div>-->
                <div class="form-item row">
                    <div class="label">
                        <label>状态</label>
                    </div>
                    <div class="body">
                        <label style="margin-right:10px;">
                            <input class="input" type="radio" name="status" value="1" th:text="禁用"
                                   style="margin-right:5px;">
                        </label>
                        <label style="margin-right:10px;">
                            <input class="input" type="radio" name="status" value="0" th:text="启用"
                                   style="margin-right:5px;">
                        </label>
                    </div>
                </div>
            </form>
            <div class="z-btn-group">
                <a class="btn-submit z-btn z-primary user-comfirm">确定</a>
                <a class="z-btn z-default" data-popup-close="">取消</a>
            </div>
        </div>
    </div>
    <div class="popup-detail section z-hide"></div>
</div>

<script th:src="@{/lib/jquery.min.js}"></script>
<script th:src="@{/lib/layer-v3.1.1/layer/layer.js}"></script>
<script th:src="@{/js/popup.js}"></script>
<script th:src="@{/js/form.js}"></script>
<script th:src="@{/js/admin/app.js}"></script>
<script th:src="@{/js/pagination.js}"></script>
<script type="text/javascript" th:inline="javascript">
    //获取context path
    var context = $("meta[name='ctx']").attr("content") || '';
    $(function () {
        eventEmit();
    })

    var departmentid = null;
    //部门关联城市列表
    var departmentCity = null;
    // 禁用的城市
    var departmentCityDisabled = null;

    function eventEmit() {
        // 新增 - 弹窗打开
        $('.btn-add').click(function () {
            departmentCity = null;
            departmentCityDisabled = null;
            $('.popup-add').formLoad({
                departmentId: '',
                departmentName: '',
                departmentCode: '',
                parentName: '',
                status: 0,
            })
            popup.open('.popup-add')
        })

        // 修改 - 弹窗打开
        $('.btn-detail').click(function () {
            var data = $(this).parents('tr')[0].dataset;
            //取值
            departmentid = data["id"];
            var departmentname = data["departmentname"];
            var departmentcode = data["departmentcode"];
            var parentdepartmentname = data["parentdepartmentname"];
            var status = data["status"];
            //取值
            var url = "/area/listDepartmentAndSelectedCity";
            if (context) {
                url = context + url;
            }
            if (departmentid) {
                url = url + "?departmentId=" + departmentid;
            }
            $.ajax({
                type: "POST",
                url: url,
                async:false,
                success: function (obj) {
                    var code = obj.code;
                    if(code == 0){
                        departmentCity = obj.data.city;
                        departmentCityDisabled = obj.data.disabled;
                    }
                }
            })

            $('.popup-detail').html($('.popup-add').html()).find('.title').text('修改');
            $('.popup-detail').formLoad({
                departmentId: departmentid,
                departmentName: departmentname,
                departmentCode: departmentcode,
                parentName: parentdepartmentname,
                status: status,
            })
            //获取部门管理的城市
            var departmentUrl = "/area/listCityByDeparmentId";
            if (context) {
                departmentUrl = context + departmentUrl;
            }
            if (departmentid) {
                departmentUrl = departmentUrl + "?departmentId=" + departmentid;
            }
            $.ajax({
                type: "POST",
                url: departmentUrl,
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        var names = [];
                        var codes = [];
                        for (var i = 0; i < obj.data.length; i++) {
                            var item = obj.data[i];
                            var name = item["name"];
                            var code = item["code"];

                            names.push(name);
                            codes.push(code);
                        }

                        names.join(',');
                        codes.join(",");

                        $('.popup-detail input[name=cityCodes]').val(codes);
                        $('.popup-detail input[name=cityNames]').val(names);
                        $('.popup-detail input[name=cityNames1]').val(names);
                    }
                }
            })
            popup.open('.popup-detail');
        })

        var url = "/department/goDepartmentPickerPage"
        if (context) {
            url = context + url;
        }
        // 选择父级部门
        $(document).on('click', '.select-parent', function () {
            layer.open({
                type: 2 //此处以iframe举例
                , title: '选择父部门'
                , area: ['900px', '500px']
                , maxmin: true
                , content: url
                , btn: ['确定', '取消'] //只是为了演示
                , btnAlign: 'c'
                , yes: function (index, layero) {
                    // 获取layer中的数据
                    var iframeWin = window[layero.find('iframe')[0]['name']] //得到iframe页的窗口对象，执行iframe页的方法
                    // 用iframeWin.functionname() 调用窗口中的方法
                    // var data = iframeWin.getData()
                    var data = iframeWin.getTreeData();

                    if (data) {
                        $('input[name=parentName]').val(data.namedata);
                        $('input[name=parentId]').val(data.idsdata);
                        layer.close(index) //如果有数据，需进行手工关闭
                    }
                }
                , btn2: function (index, layero) {
                    layer.closeAll()
                }

                , zIndex: layer.zIndex //重点1
                , success: function (layero) {
                    layer.setTop(layero) //重点2
                }
            })

        })

        //获取部门关联的城市和已被选择的城市
        $(document).on('click', '.select-city', function () {
                //选择城市
                var cityUrl = "/department/goSelectCity";
                if (context) {
                    cityUrl = context + cityUrl;
                }
                if (departmentCity) {
                    cityUrl = cityUrl + "?city=" + encodeURIComponent(JSON.stringify(departmentCity)) + "&disabled=" + encodeURIComponent(JSON.stringify(departmentCityDisabled));
                    console.log( "cityUrl :",departmentCity);
                }
                layer.open({
                    type: 2 //此处以iframe举例
                    , title: '选择城市'
                    , area: ['900px', '500px']
                    , maxmin: true
                    , content: cityUrl
                    , btn: ['确定', '取消'] //只是为了演示
                    , btnAlign: 'c'
                    , yes: function (index, layero) {
                        // 获取layer中的数据
                        var iframeWin = window[layero.find('iframe')[0]['name']] //得到iframe页的窗口对象，执行iframe页的方法
                        // 用iframeWin.functionname() 调用窗口中的方法
                        // var data = iframeWin.getData()
                        var data = iframeWin.getSelectCity();
                        var names = [];
                        var codes = [];

                        var newDepartmentCity = []
                        for (var i = 0; i < data.length; i++) {
                            var item = data[i];
                            var name = item["name"];
                            var code = item["code"];

                            names.push(name);
                            codes.push(code);

                            newDepartmentCity.push({
                                name:name,
                                code:code,
                            })
                        }

                        departmentCity = newDepartmentCity;

                        names.join(',');
                        codes.join(",");

                        if (data) {
                            if(!$('.popup-add').hasClass('z-hide')){
                                $('.popup-add input[name=cityCodes]').val(codes);
                                $('.popup-add input[name=cityNames]').val(names);
                                $('.popup-add input[name=cityNames1]').val(names);
                            }else{
                                $('.popup-detail input[name=cityCodes]').val(codes);
                                $('.popup-detail input[name=cityNames]').val(names);
                                $('.popup-detail input[name=cityNames1]').val(names);
                            }

                            layer.close(index) //如果有数据，需进行手工关闭
                        }
                    }
                    , btn2: function (index, layero) {
                        layer.closeAll()
                    }
                    , zIndex: layer.zIndex //重点1
                    , success: function (layero) {
                        layer.setTop(layero) //重点2
                    }
                })
        })
    }

    // 从URL加载搜索数据
    $(".filter").formLoad(App.query);

    //处理分页
    var pageNum = [[${pageNum}]];
    var pageSize = [[${pageSize}]];
    var total = [[${total}]];
    var pagination = new Pagination(".pagination", {
        pageIndex: pageNum, // 当前页数
        pageSize: pageSize, // 每页数量
        count: total, // 总条数
        maxButtonCount: 5, // 分页按钮数量(可选)
        // 分页切换事件
        onPageChanged: function (pageIndex) {
            window.location.href = context + "/department/list?pageNum=" + pageIndex + "&pageSize=" + pageSize;
        }
    })


    // 新增 - 弹窗保存
    var form = $(".popup-add form").form({
        submitSelector: ".popup-add .btn-submit",
        msg: function (msg) {
            popup.tipsTop(msg, 'warning');
        },
        submit: function () {
            var data = {};
            $.each($(".popup-add form").serializeArray(), function (index, field) {
                if (data[field.name]) {
                    data[field.name] += "," + field.value;
                } else {
                    data[field.name] = field.value;
                }
            })
            console.log(data);
            $.ajax({
                type: "POST",
                url: context + "/department/save",
                data: data,
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('创建部门成功', 'success');
                        setTimeout(function (args) {
                            //跳转到用户列表
                            window.location.href = context + "/department/list";
                        }, 100);
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        }
    })


    // 修改 - 弹窗确定
    var form = $(".popup-detail form").form({
        submitSelector: ".popup-detail .btn-submit",
        msg: function (msg) {
            popup.tipsTop(msg, 'warning');
        },
        submit: function () {
            var data = {};
            $.each($(".popup-detail form").serializeArray(), function (index, field) {
                if (data[field.name]) {
                    data[field.name] += "," + field.value;
                } else {
                    data[field.name] = field.value;
                }
            })
            console.log(data);
            //修改
            $.ajax({
                type: "POST",
                url: context + "/department/update",
                data: data,
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('修改部门成功', 'success');
                        setTimeout(function (args) {
                            //跳转到用户列表
                            window.location.href = context + "/department/list";
                        }, 1000);
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        }
    })

    // 启用/禁用
    $('.btn-disable,.btn-enable').click(function () {
        var data = $(this).parents('tr')[0].dataset;
        var id = data["id"];
        //默认（0：启用）
        var status = 0;
        if ($(this).hasClass('btn-enable')) {
            $.ajax({
                type: "POST",
                url: context + "/department/enableDisableDepartment",
                data: {
                    departmentId: id,
                    status: status
                },
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('enable', '启用部门成功');
                        //跳转到用户列表
                        window.location.href = context + "/department/list";
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        } else {
            //禁用
            status = 1;
            $.ajax({
                type: "POST",
                url: context + "/department/enableDisableDepartment",
                data: {
                    departmentId: id,
                    status: status
                },
                success: function (obj) {
                    var code = obj.code;
                    if (code == 0) {
                        popup.tipsTop('disable', '禁用部门成功');
                        //跳转到用户列表
                        window.location.href = context + "/department/list";
                    } else {
                        popup.tipsTop(obj.msg, 'warning');
                    }
                }
            })
        }
    })

    // 批量启用禁用部门
    $('.btn-batch-able, .btn-batch-disable').click(function () {
        var status = 0;
        var optName = "批量启用";
        if($(this).hasClass('btn-batch-disable')){
            status = 1;
            optName = "批量禁用";
        }

        let idArr = [];
        $('tbody [type="checkbox"]').each(function (index, element) {
            if (element.checked == true) {
                var id = $(this).parents('tr,.tr').data('id');
                idArr.push(id);
            }
        })
        var ids = idArr.join(',');
        if(isBlank(ids)){
            popup.tipsTop('请选择需要'+optName+'的部门', 'warning');
            return;
        }
        $.ajax({
            type: "POST",
            url: context + "/department/batchAbleDisable",
            data: {
                ids: ids,
                status: status
            },
            success: function (obj) {
                var code = obj.code;
                if (code == 0) {
                    popup.tipsTop((optName + '成功'), 'success');
                    setTimeout(function () {
                        //跳转到部门列表
                        window.location.href = context + "/department/list";
                    }, 1000);
                } else {
                    popup.tipsTop(obj.msg, 'warning');
                }
            }
        })
    })

    //检查参数
    function isBlank(param) {
        if(undefined === param){
            return true;
        }
        if(null == param){
            return true;
        }
        if("" === param){
            return true;
        }
        return false;
    }
</script>
</body>

</html>